<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends CI_Controller {

    private $username = null;
    private $password = null;
    private $user_id = null;

    public function index() {
        $this->load->view('login');
    }

    public function check_login_data() {
        $this->username = $this->input->post('username');
        $this->password = $this->input->post('password');

        $this->form_validation->set_rules('username', 'user check', 'callback_user_data_check');
        $this->form_validation->set_message('user_data_check', 'Nu există așa administrator!');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->form_validation->run() == true) {
            $this->add_user_to_session();
            redirect('home');
        } else {
            $this->load->view('login');
        }
    }

    public function logout() {
        $this->remove_user_from_session();
        redirect('login');
    }

    //functie callback pentru verificarea existentei utilizatorului
    public function user_data_check() {
        $getUserSqlString = 'SELECT * FROM users WHERE username = ? AND password = ? AND removal_date IS NULL AND type = ? LIMIT 1';
        $query = $this->db->query($getUserSqlString, array($this->username, $this->password, User_types::ADMIN));

        if ($query->num_rows() == 1) {
            $this->user_id = $query->row()->id;
            return true;
        } else {
            return false;
        }
    }

    private function add_user_to_session() {
        $this->session->set_userdata('user_id', $this->user_id);
    }

    private function remove_user_from_session() {
        $this->session->unset_userdata('user_id');
    }

}

?>